package typ

import (
	"bytes"
	"regexp"
	"strings"
)

var MobileSplit = "-"
var DefGlobal = "86"

// IsPhone
func IsPhone(phone string) bool {
	reg := regexp.MustCompile(`^\d{1,4}-\d{6,11}$`)
	flag := reg.MatchString(phone)
	return flag
}

// IsChinesePhone
func IsChinesePhone(phone string) bool {
	if IsPhone(phone) {
		return strings.HasPrefix(phone, "86-") || !strings.Contains(phone, "-")
	} else {
		return false
	}
}

// HidePhoneMiddle eg：86-187****0987
func HidePhoneMiddle(phone string) string {
	hidden := "****"
	if phone == "" {
		return hidden
	}
	arr := strings.Split(phone, "-")
	if len(arr) != 2 {
		return hidden
	}
	number := arr[1]
	if len(number) < 7 {
		return hidden
	}
	prefix := number[0:3]
	suffix := number[len(number)-4:]

	var buf bytes.Buffer
	buf.WriteString(arr[0])
	buf.WriteString("-")
	buf.WriteString(prefix)
	buf.WriteString(hidden)
	buf.WriteString(suffix)

	return buf.String()
}

func GlobalMobile(mobile string) string {
	if mobile == "" {
		return mobile
	}
	if strings.Contains(mobile, MobileSplit) {
		return mobile
	}
	return DefGlobal + MobileSplit + mobile //默认国内手机号
}

// MakeGlobalMobile 第一个是国际区号
// 第二个为区号后面的手机号
func MakeGlobalMobile(mobile string) (string, string) {
	if mobile == "" {
		return mobile, mobile
	}
	if strings.Contains(mobile, MobileSplit) {
		split := strings.Split(mobile, MobileSplit)
		if len(split) >= 2 {
			return split[0], split[1]
		}
	}
	return DefGlobal, mobile
}

// IsGlobalMobile 验证是否为国际手机号码
func IsGlobalMobile(mobile string) bool {
	if mobile == "" {
		return false
	}
	if strings.Contains(mobile, MobileSplit) {
		split := strings.Split(mobile, MobileSplit)
		if len(split) != 2 {
			return false
		}
		return IsNumber(split[0]) && IsNumber(split[1])
	}
	return IsNumber(mobile)
}

func IsNumber(str string) bool {
	if str == "" {
		return false
	}
	match, _ := regexp.MatchString("^[0-9]+$", str)
	return match
}
